from dailyspents.model import orm
from dailyspents._exceptions import DatabaseException
from sqlalchemy import desc
from sqlalchemy.exceptions import *
from sqlalchemy.ext.selectresults import SelectResults
from GenericController import GenericController

class SpentController(GenericController):
    
    def __init__(self, user):
        GenericController.__init__(self, user, orm.Spent)
    
    def getAll(self):
        res = SelectResults(self.query)
        res = res.order_by(desc(orm.Spent.c.date))
        res = res.filter(orm.Spent.c.user_id == self.user.id)
        return list(res)
    
    def getByOffsetLimit(self, offset, limit):
        return self.getAll()[offset : limit]
    
    def getByCategory(self, category_, offset=None, limit=None):
        return self.query.select_by(category=category_, 
                                    user=self.user)[offset:limit]
    
    def getTotalByCategory(self, cat):
        res = SelectResults(self.query)
        return res.filter(orm.Spent.c.cotegory_id==cat.id).count()
    
    def getTotalByPayment(self, pay):
        res = SelectResults(self.query)
        return res.filter(orm.Spent.c.payment_id==pay.id).count()
    
    def getByPayment(self, payment_, offset=None, limit=None):
        return self.query.select_by(payment=payment_, 
                                    user=self.user)[offset:limit]
    
    def filter(self, dateInterval=None, value=None, catId=None,
               payId=None, localId=None, description=None):
        
        res = SelectResults(self.query)
        
        if dateInterval[0] != None and dateInterval[1] != None:
            res = res.filter(orm.Spent.c.date.between(dateInterval[0],\
                                      dateInterval[1]))
        if value is not None:
            res = res.filter(orm.Spent.c.value == float(eval(value)))
            
        if catId is not None:
            res = res.filter(orm.Spent.c.cotegory_id == int(catId))
            
        if payId is not None:
            res = res.filter(orm.Spent.c.payment_id == int(payId))
            
        if localId is not None:
            res = res.filter(orm.Spent.c.local_id == int(localId))
            
        if description is not None:
            res = res.filter(orm.Spent.c.description.like('%'+description+'%'))
        
        res = res.order_by(desc(orm.Spent.c.date))
        return list(res)
